<template>
  <div class="community-container">
    <!-- 顶部导航栏 -->
    <div class="community-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="site-title">智绘灵图社区</h1>
          <div class="search-box">
            <a-input-search
              v-model:value="searchParams.searchText"
              placeholder="输入文章、标签进行搜索"
              style="width: 300px"
              @search="onSearch"
            />
          </div>
        </div>
        <div class="header-right">
          <RouterLink to="/community/createPost">
            <a-button class="submit-button">
              <edit-outlined />
              写文章
            </a-button>
          </RouterLink>
        </div>
      </div>
    </div>

    <!-- 主体内容区 -->
    <div class="community-content">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div class="sidebar-menu">
          <div class="menu-item" @click="navigateToCommunity">
            <home-outlined />
            <span>推荐</span>
          </div>
          <div class="menu-item active">
            <fire-outlined />
            <span>发现</span>
          </div>
          <div class="menu-item">
            <star-outlined />
            <span>收藏</span>
          </div>
        </div>

        <div class="sidebar-divider"></div>

        <div class="sidebar-tags">
          <h3>热门标签</h3>
          <div class="tag-list">
            <a-tag
              v-for="(tag, index) in postTags"
              :key="index"
              :color="getTagColor(tag.category)"
              class="tag-item"
            >{{ tag.name }}</a-tag
            >
          </div>
        </div>
      </div>

      <!-- 中间文章列表 -->
      <div class="main-content">
        <div class="discovery-header">
          <h1 class="page-title">发现</h1>
          <p class="page-subtitle">发现和探索最受欢迎的社区&标签</p>
        </div>

        <!-- 文章类型标签页 -->
        <div class="article-type-tabs">
          <div
            class="type-tab"
            :class="{ active: articleType === '热门文章' }"
            @click="selectArticleType('热门文章')"
          >
            热门文章
          </div>
          <div
            class="type-tab"
            :class="{ active: articleType === '讨论/问答' }"
            @click="selectArticleType('讨论/问答')"
          >
            讨论/问答
          </div>
          <div
            class="type-tab"
            :class="{ active: articleType === '直播' }"
            @click="selectArticleType('直播')"
          >
            直播
          </div>
          <div
            class="type-tab"
            :class="{ active: articleType === '课程' }"
            @click="selectArticleType('课程')"
          >
            课程
          </div>
        </div>

        <!-- 标签选择区 -->
        <div class="tags-container">
          <div class="category-section">
<!--            <div class="category-label">全部：</div>-->
            <div class="tag-list-horizontal">
              <a-tag
                class="tag-item"
                :class="{ active: selectedTag === '全部' }"
                :color="getTagColor('全部')"
                @click="selectTag('全部')"
              >
                全部
              </a-tag>
              <a-tag
                v-for="tag in postTags"
                class="tag-item"
                :key="tag.id"
                :class="{ active: selectedTag === tag.name }"
                :color="getTagColor(tag.category)"
                @click="selectTag(tag?.category || '')"
              >
                {{ tag.name }}
              </a-tag>
            </div>
          </div>

        </div>

        <!-- 文章列表 -->
        <div class="article-list">
          <div v-if="loading" class="loading-container">
            <a-spin />
          </div>
          <template v-else>
            <div
              v-for="post in filteredPosts"
              :key="post.id"
              class="article-item"
              @click="viewArticle(post.id || 0)"
            >
              <div class="article-content">
                <h2 class="article-title" v-html="highlightText(post.title)"></h2>
                <p class="article-summary" v-html="highlightText(post.summary)"></p>
                <div class="article-meta">
                  <div class="author-info">
                    <img :src="post.userAvatar || '/default-avatar.png'" class="avatar" />
                    <span class="author-name">{{ post.userName }}</span>
                    <span class="time">{{
                      dayjs(post.createTime).format('YYYY-MM-DD HH:mm:ss')
                    }}</span>
                  </div>
                  <div class="stats">
                    <span class="stat-item"><eye-outlined /> {{ post.viewCount }}</span>
                    <span class="stat-item"><like-outlined /> {{ post.likeCount }}</span>
                    <span class="stat-item"><message-outlined /> {{ post.commentCount }}</span>
                  </div>
                  <div class="tags">
                    <a-tag v-for="tag in post.tagList" :key="tag" :color="getTagColor(tag)">{{
                      tag
                    }}</a-tag>
                  </div>
                </div>
              </div>
              <div class="article-image" v-if="post.imageUrl">
                <img :src="post.imageUrl" :alt="post.title" />
              </div>
            </div>

            <div v-if="filteredPosts.length === 0" class="empty-state">
              <a-empty description="暂无相关文章" />
            </div>

            <div v-if="filteredPosts.length > 0" class="pagination">
              <a-pagination
                v-model:current="currentPage"
                :total="totalPosts"
                :pageSize="pageSize"
                @change="handlePageChange"
              />
            </div>
          </template>
        </div>
      </div>

      <!-- 右侧热门内容 -->
      <div class="sidebar-right">
        <div class="community-section">
          <h3>社区推荐</h3>
          <div class="community-list">
            <div class="community-item">
              <div class="community-logo">
                <img
                  src="https://img.alicdn.com/imgextra/i1/O1CN01mWRJ8q1ZMcPzfJYxW_!!6000000003183-2-tps-200-200.png"
                  alt="华为开发者社区"
                />
              </div>
              <div class="community-info">
                <div class="community-name">华为开发者空间</div>
                <div class="community-desc">
                  华为开发者空间，是为全球开发者打造的专属开发空间，汇聚了华为开发资源...
                </div>
                <div class="community-stats">4,476,143 成员</div>
              </div>
              <div class="community-action">
                <a-button size="small">写文章</a-button>
              </div>
            </div>

            <div class="community-item">
              <div class="community-logo">
                <img
                  src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
                  alt="开放原子开发者工作坊"
                />
              </div>
              <div class="community-info">
                <div class="community-name">开放原子开发者工作坊</div>
                <div class="community-desc">
                  开放原子开发者工作坊旨在鼓励更多人参与开源活动，与志同道合的开发者们...
                </div>
                <div class="community-stats">608,478 成员</div>
              </div>
              <div class="community-action">
                <a-button size="small">+ 加入社区</a-button>
              </div>
            </div>

            <div class="community-item">
              <div class="community-logo">
                <img src="https://img01.yzcdn.cn/vant/logo.png" alt="ViewDesign" />
              </div>
              <div class="community-info">
                <div class="community-name">ViewDesign</div>
                <div class="community-desc">
                  基于 Vue.js 3 的企业级 UI 组件库和中后台系统解决方案，为数万开发者服务。
                </div>
                <div class="community-stats">407,076 成员</div>
              </div>
              <div class="community-action">
                <a-button size="small">+ 加入社区</a-button>
              </div>
            </div>
          </div>
        </div>

        <div class="hot-post-section">
          <h3>热门文章</h3>
          <div class="hot-post-list">
            <div
              v-for="(post, index) in hotCommunityPosts.slice(0, 5)"
              :key="index"
              class="hot-post-item"
              @click="viewArticle(post.id || 0)"
            >
              <div class="hot-post-title" v-html="highlightText(post?.title)"></div>
              <div class="hot-post-meta">
                <span><eye-outlined /> {{ post?.viewCount }}</span>
                <span><like-outlined /> {{ post?.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { RouterLink, useRouter, onBeforeRouteLeave } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  HomeOutlined,
  FireOutlined,
  StarOutlined,
  EditOutlined,
  EyeOutlined,
  LikeOutlined,
  MessageOutlined,
} from '@ant-design/icons-vue'
import { getTagListUsingGet } from '@/api/tagController'
import { listCommunityPostVoByPageUsingPost } from '@/api/communityPostController'
import '@/api/typings.d.ts'
// 使用 dayjs 等库格式化
import dayjs from 'dayjs'

const router = useRouter()
const activeTab = ref('hot')
const selectedTag = ref('全部')
const articleType = ref('热门文章')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPosts = ref(0)

// 搜索功能
const onSearch = () => {
  fetchPosts()
}

// 高亮显示搜索词
const highlightText = (text: string | undefined) => {
  if (!text || !searchParams.searchText || searchParams.searchText.trim() === '') return text || ''

  // 将搜索词中的特殊字符进行转义，避免正则表达式错误
  const escapeRegExp = (string: string) => {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  }

  const searchWords = searchParams.searchText
  let highlightedText = text
  const escapedWord = escapeRegExp(searchWords.trim())
  if (escapedWord) {
    const regex = new RegExp(`(${escapedWord})`, 'gi')
    highlightedText = highlightedText.replace(regex, '<span class="highlight">$1</span>')
  }
  // 应用高亮
  // searchWords.forEach((word) => {
  //   const escapedWord = escapeRegExp(word.trim())
  //   if (escapedWord) {
  //     const regex = new RegExp(`(${escapedWord})`, 'gi')
  //     highlightedText = highlightedText.replace(regex, '<span class="highlight">$1</span>')
  //   }
  // })

  return highlightedText
}


// 获取标签颜色
const getTagColor = (tag?: string | null) => {
  // 处理空值情况
  if (!tag) return '#2ad73c' // 返回默认颜色

  const colors = [
    'blue',
    'green',
    'orange',
    'purple',
    'cyan',
    'red',
    'volcano',
    'geekblue',
    'lime',
    'magenta',
  ]
  const hash = tag.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[hash % colors.length]
}

// 文章列表
const posts = ref<API.CommunityPostVO[]>([])
const hotCommunityPosts = ref<API.CommunityPostVO[]>([])

// 标签数据
const postTags = ref<API.Tag[]>([])
const popularTags = ref<API.Tag[]>([])
// 分页参数
const searchParams = reactive<API.CommunityPostQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
  searchText: '',
  hotOrder: false,
  tags: [],
})
// 热门文章参数
const hotSearchParams = reactive<API.CommunityPostQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'likeCount',
  sortOrder: 'descend',
  searchText: '',
  hotOrder: true, // 热门排序标志
})


// 过滤后的文章列表
const filteredPosts = computed(() => posts.value)

// 选择文章类型
const selectArticleType = (type: string) => {
  articleType.value = type

  // 根据选择的类型更新activeTab
  switch (type) {
    case '热门文章':
      activeTab.value = 'hot'
      break
    case '讨论/问答':
      activeTab.value = 'discussion'
      break
    case '直播':
      activeTab.value = 'live'
      break
    case '课程':
      activeTab.value = 'course'
      break
    default:
      activeTab.value = 'hot'
  }

  fetchPosts()
}

// 获取标签列表
const getPostTags = async () => {
  try {
    const response = await getTagListUsingGet()
    if (response.data.code === 0) {
      postTags.value = response.data.data || []
      popularTags.value = postTags.value.filter((tag) => tag?.followerCount !== undefined && tag.followerCount > 0).slice(0, 10)

    } else {
      message.error('获取标签列表失败，' + response.data.message)
    }
  } catch (error) {
    console.error('获取标签列表失败：', error)
    message.error('获取标签列表失败，请稍后重试')
  }
}

// 选择标签
const selectTag = (tag: string) => {
  selectedTag.value = tag
  currentPage.value = 1

  // 更新查询参数
  if (tag === '全部') {
    searchParams.tags = []
  } else {
    searchParams.tags = [tag]
  }

  fetchPosts()
}

// 查看文章详情
const viewArticle = (id: number) => {
  router.push(`/community/postDetail/${id}`)
}

// 获取文章列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const queryParams = { ...searchParams }
    queryParams.current = currentPage.value

    // 根据当前标签页设置排序
    if (activeTab.value === 'hot') {
      queryParams.sortField = 'likeCount'
      queryParams.hotOrder = true
    } else {
      queryParams.sortField = 'createTime'
      queryParams.hotOrder = false
    }

    const response = await listCommunityPostVoByPageUsingPost(queryParams, {})
    if (response.data && response.data.code === 0) {
      posts.value = response.data.data?.records || []
      totalPosts.value = response.data.data?.total || 0
    } else {
      message.error('获取文章失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取文章列表出错:', error)
    message.error('获取文章列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取热门文章 - 用于右侧栏展示
const fetchHotPosts = async () => {
  try {
    const response = await listCommunityPostVoByPageUsingPost(hotSearchParams, {})
    if (response.data && response.data.code === 0) {
      hotCommunityPosts.value = response.data.data?.records || []
    }
  } catch (error) {
    console.error('获取热门文章失败:', error)
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPosts()
}

// 导航到社区主页
const navigateToCommunity = () => {
  router.push('/community')
}

// 路由销毁逻辑
onBeforeRouteLeave((to, from, next) => {
  // 在这里可以执行任何清理操作
  posts.value = []
  hotCommunityPosts.value = []
  next()
})

// 页面加载时获取数据
onMounted(() => {
  getPostTags()
  fetchPosts()
  fetchHotPosts()
})

// 页面卸载前清理资源
onBeforeUnmount(() => {
  posts.value = []
  hotCommunityPosts.value = []
})
</script>

<style scoped>
/* 引入社区页面的样式 */
.community-container {
  max-width: 100%;
  min-height: 100vh;
  background-color: #f7f8fa;
}

/* 顶部导航栏样式 */
.community-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.site-title {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
  color: #1890ff;
}

.search-box {
  margin-left: 20px;
}

/* 主体内容样式 */
.community-content {
  max-width: 1400px;
  margin: 20px auto;
  display: grid;
  grid-template-columns: 200px 1fr 300px;
  gap: 20px;
  padding: 0 20px;
}

/* 左侧侧边栏样式 */
.sidebar {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.sidebar-menu {
  margin-bottom: 20px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 5px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f0f7ff;
}

.menu-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

.menu-item span {
  margin-left: 10px;
}

.sidebar-divider {
  height: 1px;
  background-color: #f0f0f0;
  margin: 15px 0;
}

.sidebar-tags h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
  margin-bottom: 8px;
}

/* 中间主内容样式 */
.main-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

/* 文章类型标签页 */
.article-type-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.type-tab {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  color: #666;
  font-weight: 500;
  transition: all 0.3s;
}

.type-tab.active {
  color: #1890ff;
}

.type-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  border-radius: 1px;
}

.type-tab:hover {
  color: #1890ff;
}

/* 标签选择区样式 */
.tags-container {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
}

.category-section {
  display: flex;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.category-section:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.category-label {
  font-size: 14px;
  font-weight: 500;
  color: #666;
  width: 90px;
  line-height: 32px;
  flex-shrink: 0;
}

.tag-list-horizontal {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 0;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tag-item.active {
  background-color: #1890ff !important;
  color: white !important;
}

/* 右侧内容样式 */
.sidebar-right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.community-section,
.hot-post-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.community-section h3,
.hot-post-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
  font-weight: bold;
}

.community-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.community-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.community-item:last-child {
  border-bottom: none;
}

.community-logo {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.community-logo img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 4px;
}

.community-info {
  flex: 1;
}

.community-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.community-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.community-stats {
  font-size: 12px;
  color: #666;
}

.community-action {
  display: flex;
  align-items: center;
}

.hot-post-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.hot-post-item {
  padding: 8px 0;
  cursor: pointer;
}

.hot-post-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
  line-height: 1.5;
}

.hot-post-title:hover {
  color: #1890ff;
}

.hot-post-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  gap: 10px;
}

/* 发现页面特有样式 */
.discovery-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
}

.nav-tabs {
  display: none; /* 隐藏原来的导航标签 */
}

.article-list {
  margin-top: 20px;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.article-item {
  display: flex;
  padding: 20px;
  border-radius: 8px;
  background: white;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.article-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.article-content {
  flex: 1;
  margin-right: 20px;
}

.article-title {
  font-size: 18px;
  margin-bottom: 10px;
  font-weight: 600;
  color: #333;
}

.article-summary {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
  font-size: 13px;
  color: #888;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.author-name {
  color: #555;
}

.time {
  color: #999;
  font-size: 12px;
}

.stats {
  display: flex;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.article-image {
  width: 160px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
}

.article-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

.highlight {
  color: #ff4d4f;
  font-weight: bold;
  background-color: rgba(255, 77, 79, 0.1);
  padding: 0 2px;
  border-radius: 2px;
}

/* 提交按钮样式 */
:deep(.submit-button) {
  background: linear-gradient(135deg, #ff8e53 0%, #ff6b6b 100%);
  border: none;
  color: white;
  width: 150px;
  height: 40px;
  border-radius: 22px;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
  transition: all 0.3s ease;
}

:deep(.submit-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(255, 107, 107, 0.3);
}

:deep(.submit-button:active) {
  transform: translateY(1px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .community-content {
    grid-template-columns: 200px 1fr;
  }

  .sidebar-right {
    display: none;
  }
}

@media (max-width: 768px) {
  .community-content {
    grid-template-columns: 1fr;
  }

  .sidebar {
    display: none;
  }

  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-box {
    margin-left: 0;
  }

  .article-item {
    flex-direction: column;
  }

  .article-content {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .article-image {
    width: 100%;
    height: 180px;
  }

  .category-section {
    flex-direction: column;
  }

  .category-label {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>
